//
//  BindingController.swift
//  newshaohuo
//
//  Created by shaohuo on 2018/1/31.
//  Copyright © 2018年 shaohuo. All rights reserved.
//

import Foundation
import SwiftProgressHUD

protocol BindingControllerDelegate {
    
    func bindingControllerDissmiss()
}

class BindingController: UIViewController,SwiftyVerificationCodeViewDelegate {
    
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var subTitleLabel: UILabel!
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var phoneView: UIView!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var testButton: UIButton!
    
    @IBOutlet weak var verificationView: UIView!
    @IBOutlet weak var verificationButton: UIButton!
    @IBOutlet weak var codeView: VerificationCodeView!
    @IBOutlet weak var verifacationTextField: UITextField!
    
    @IBOutlet weak var verificationCodeView: UIView!
    @IBOutlet weak var countDownButton: UIButton!
    
    var delegate : BindingControllerDelegate!
    
    var codeV : VerificationCodeView!
    
    var leftTime:Int = 60
    
    var timer :Timer!
    
    var openidString : String!
    
    var unionidString : String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置内容区域
        scrollView.contentSize = CGSize(width: 3*kScreenWitdh, height: 200)
        //是否显示水平滚动条
        scrollView.showsHorizontalScrollIndicator = false
        //是否显示竖直滚动条
        scrollView.showsVerticalScrollIndicator = false
        //设置分页滚动
        scrollView.isPagingEnabled = true
        //允许滑动视图本身，如果设为false就不能触发拖动代理事件
        scrollView.isScrollEnabled = false
        
        phoneView.layer.borderWidth = 0.5
        phoneView.layer.borderColor = UIColor.init(hexString: "#B7B7B7").cgColor
        
        testButton.layer.borderWidth = 0.5
        testButton.layer.borderColor = UIColor.init(hexString: "#B7B7B7").cgColor
        
        verificationView.layer.borderWidth = 0.5
        verificationView.layer.borderColor = UIColor.init(hexString: "#B7B7B7").cgColor
        
        verificationButton.layer.borderWidth = 0.5
        verificationButton.layer.borderColor = UIColor.init(hexString: "#B7B7B7").cgColor
        
        codeV = VerificationCodeView(frame: codeView.bounds)
        
        codeView.addSubview(codeV)
        
        let v = SwiftyVerificationCodeView(frame: verificationCodeView.bounds)
        v.delegate = self
        view.backgroundColor = UIColor.white
        verificationCodeView.addSubview(v)

    }
    
    func requestSendCaptcha(command:String,type:String,source:String,mobile:String,code:String,captcha:String,openid:String,unionid:String,client:String) -> Void {
        //要加密的数据
        let param = ["command":command,"type":type,"source":source,"mobile":mobile,"code":code,"captcha":captcha,"openid":openid,"unionid":unionid]
        
        NetworkTools.sharedInstance.postRequest(urlString: "", parameters: param as AnyObject, headers: ["copyright":"v1","interface":"Login"], successed: { (resultDict) in
            
            if !captcha.isEmpty {
                
                let data = resultDict["data"] as! [String:AnyObject]
                self.saveUserInfo(data: data)
                self.delegate?.bindingControllerDissmiss()
                
            }

        })
    }
    
    //保存用户信息
    func saveUserInfo(data:[String:AnyObject]) {
        if let uid = data["uid"] as? String {
            UserTicketModel.sharedInstance.uid = uid
        }
        if let token = data["shraccess_token"] as? String {
            UserTicketModel.sharedInstance.token = token
        }
        if let mobile = data["mobile"] as? String {
            UserTicketModel.sharedInstance.phone = mobile
        }
        if let real_name = data["real_name"] as? String {
            UserTicketModel.sharedInstance.name = real_name
        }
        if let nick_name = data["nick_name"] as? String {
            UserTicketModel.sharedInstance.nick = nick_name
        }
        if let header_img = data["header_img"] as? String {
            UserTicketModel.sharedInstance.headerImg = header_img
        }
        if let signature = data["signature"] as? String {
            UserTicketModel.sharedInstance.perm = signature
        }
        if let type = data["type"] as? String {
            UserTicketModel.sharedInstance.user_type = Int(type)
        }
        
        //默认打开声音
        UserNotificationSettingModel.sharedInstance.is_voice_off = true
        //默认播放男声
        UserNotificationSettingModel.sharedInstance.is_voice_sex = "new_order"
        
        self.dismiss(animated: true, completion: nil)
    }
    
    @IBAction func dismissBtnAction(_ sender: UIButton) {
        
        dismiss(animated: true, completion: nil)
    }
    
    //发送验证码
    @IBAction func testBtnAction(_ sender: UIButton) {
        
        if phoneTextField.text!.isEmpty {
            SwiftProgressHUD.showOnlyText("请输入手机号")
        }else {

            //设置偏移量，以固定的速度设置成新的偏移量
            self.scrollView.setContentOffset(CGPoint(x:kScreenWitdh,y:0), animated: true)
            self.titleLabel.text = "需要身份验证"
            
        }
    
    }
    //验证
    @IBAction func verificationBtnAction(_ sender: UIButton) {
        
        if verifacationTextField.text!.isEmpty {
            SwiftProgressHUD.showOnlyText("请输入验证码")
            
        }else {
            
            let result = codeV.startAuthWithString(verify: verifacationTextField.text!)
            
            if result {
                
                requestSendCaptcha(command: "sendCaptcha", type: "bind", source: "wx",mobile:phoneTextField.text!, code: "",captcha:"",openid:"",unionid:"",client:"")
                
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                    //设置偏移量，以固定的速度设置成新的偏移量
                    self.scrollView.setContentOffset(CGPoint(x:2*kScreenWitdh,y:0), animated: true)
                    self.titleLabel.text = "输入验证码"
                    self.subTitleLabel.isHidden = false
                    self.subTitleLabel.text = "验证码已发至+86 \(self.phoneTextField.text!)"
                }

            }else {
                
                SwiftProgressHUD.showOnlyText("验证码错误")
            }
        }
    }
    //看不清，换一张
    @IBAction func changeBtnAction(_ sender: UIButton) {
        
        codeV.reloadAuthCodeView()
        
    }
    
    //重发短信验证码
    @IBAction func resendTestBtnAction(_ sender: UIButton) {
        
        requestSendCaptcha(command: "sendCaptcha", type: "bind", source: "wx",mobile:phoneTextField.text!, code: "",captcha:"",openid:"",unionid:"",client:"")
        
        leftTime = 60
        sender.setTitle("重新计时(\(leftTime)S)", for: .disabled)
        sender.isEnabled = false
        //获取该计时器的剩余时间
        timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(tickDown), userInfo: nil, repeats: true)
        
    }
    
    @objc func tickDown() {
        //将剩余时间减少1秒
        leftTime -= 1
        //修改UIDatePicker的剩余时间
        countDownButton.setTitle("重新计时(\(leftTime)S)", for: .disabled)
        //如果剩余时间小于等于0
        if leftTime <= 0 {

            //取消定时器
            timer.invalidate()
            countDownButton.isEnabled = true
            countDownButton.setTitle("重发短信验证", for: .normal)
        
        }
    }
    
    
    func verificationCodeDidFinishedInput(verificationCodeView: SwiftyVerificationCodeView, code: String) {
  
        requestSendCaptcha(command: "loginOrregister",type: "bind", source: "wx",mobile:phoneTextField.text!, code: "",captcha:code,openid:openidString,unionid:unionidString,client:"")
        
        if code != "4396" {
            verificationCodeView.cleanVerificationCodeView()
        }
    }
}
